﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GtsServer.Model;
using System.Timers;
using GtsServer.DAL;
using System.Data;
using GtsServer.Common;

namespace GtsServer.Service.TaskStartEndService
{
    public class TaskController
    {
        private static TaskController taskController = null;
        static object objLock = new object();
        //待开始任务集合
        Dictionary<int, Task> dictStartTask = new Dictionary<int, Task>();
        //待结束任务集合
        Dictionary<int, Task> dictEndTask = new Dictionary<int, Task>();
        TaskDAL dal = new TaskDAL();

        /// <summary>
        /// 比赛的机器人计时器集合
        /// </summary>
        Dictionary<int, TaskRobotController> dictTimerController = new Dictionary<int, TaskRobotController>();

        /// <summary>
        /// 获取所有的机器人  key：index
        /// </summary>
        public static Dictionary<int, User> dictRobotUser = new Dictionary<int, User>();

        public static TaskController GetInstance()
        {
            if (taskController == null)
            {
                lock (objLock)
                {
                    if (taskController == null)
                    {
                        taskController = new TaskController();
                    }
                }
            }
            return taskController;
        }

        private TaskController()
        {
            LogHelper.WriteLog("开始结束任务服务开启中...");
            Load();
            LogHelper.WriteLog("开始、结束任务集合加载完毕！待开始任务count：" + dictStartTask.Count + "，待结束任务count：" + dictEndTask.Count);

            //开始任务计时器
            Timer startTimer = new Timer(30000);
            startTimer.Elapsed += new ElapsedEventHandler(StartTimer_Elapsed);
            startTimer.Start();
            LogHelper.WriteLog("待开始任务timer已启动！");

            //结束任务计时器
            Timer endTimer = new Timer(30000);
            startTimer.Elapsed += new ElapsedEventHandler(EndTimer_Elapsed);
            startTimer.Start();
            LogHelper.WriteLog("待结束任务timer已启动！");
        }

        #region 定时开关  任务
        public void Delete(int id)
        {
            lock (objLock)
            {
                if (dictStartTask.ContainsKey(id))
                    dictStartTask.Remove(id);
            }
            lock (objLock)
            {
                if (dictStartTask.ContainsKey(id))
                    dictStartTask.Remove(id);
            }
        }


        private void Load()
        {
            DataSet ds = dal.GetListByState();
            List<Task> list = IListDataSet.DataSetToIList<Task>(ds, 0).ToList();

            foreach (var item in list)
            {
                if (item.State.Equals(Convert.ToInt32(EnumTaskState.未开始)))
                {
                    if (!dictStartTask.ContainsKey(item.ID))
                        dictStartTask[item.ID] = new Task();
                    dictStartTask[item.ID] = item;
                }
                else if (item.State.Equals(Convert.ToInt32(EnumTaskState.进行中)))
                {
                    if (!dictEndTask.ContainsKey(item.ID))
                        dictEndTask[item.ID] = new Task();
                    dictEndTask[item.ID] = item;
                }
            }

            List<User> userList = IListDataSet.DataSetToIList<User>(ds, 1).ToList();

            foreach (var user in userList)
            {
                if (!dictRobotUser.ContainsKey(user.RobotIndex))
                    dictRobotUser[user.RobotIndex] = new User();
                dictRobotUser[user.RobotIndex] = user;
            }

            //加载比赛机器人
            foreach (var item in dictEndTask)
            {
                 ds = new DataSet();
                ds = dal.GetListByTaskID(item.Value.ID);

                if (ds.Tables[1].Rows.Count > 0)
                {
                    TaskRobotSetting model = IListDataSet.DataSetToIList<TaskRobotSetting>(ds, 1).ToList().First();
                    if (!dictTimerController.ContainsKey(item.Value.ID))
                        dictTimerController[item.Value.ID] = new TaskRobotController(model);

                    //加载已参加的机器人id
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            int userID = Convert.ToInt32(row["userID"]);
                            if (!dictTimerController[item.Value.ID].hsUserID.Contains(userID))
                                dictTimerController[item.Value.ID].hsUserID.Add(userID);
                        }
                    }
                    LogHelper.WriteLog("任务id为" + item.Value.ID + "的机器人计时器已开启，共有" + dictTimerController[item.Value.ID].hsUserID.Count + "个机器人参加！");
                }
            }
        }

        public void EditTask(Task model)
        {
            if (!dictStartTask.ContainsKey(model.ID))
                dictStartTask[model.ID] = new Task();
            dictStartTask[model.ID] = model;
        }

        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void StartTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string ids = "";
            foreach (var item in dictStartTask)
            {
                if (item.Value.StartTime <= DateTime.Now)
                    ids += "," + item.Value.ID;
            }

            if (!string.IsNullOrEmpty(ids))
            {
                ids = ids.Substring(1);
                bool isSuccess = dal.Update(ids, Convert.ToInt32(GtsServer.Model.EnumTaskState.进行中));

                if (isSuccess)
                {
                    string[] indexes = new string[] { };
                    if (ids.IndexOf(',') > 0)
                        indexes = ids.Split(',');
                    else
                        indexes = new string[] { ids };

                    foreach (var item in indexes)
                    {
                        int id = Convert.ToInt32(item);
                        //加入待结束任务集合中
                        if (!dictEndTask.ContainsKey(id))
                            dictEndTask[id] = new Task();
                        dictEndTask[id] = dictStartTask[id];
                        //删除待开始任务中的项
                        dictStartTask.Remove(id);
                    }
                }

                //获取开始任务的  机器人设置
                DataSet ds = dal.GetRobotSetting(ids);
                List<TaskRobotSetting> list = IListDataSet.DataSetToIList<TaskRobotSetting>(ds, 0).ToList();
                foreach (var item in list)
                {
                    if (!dictTimerController.ContainsKey(item.TaskID.Value))
                        dictTimerController[item.TaskID.Value] = new TaskRobotController(item);
                }
            }
        }
        /// <summary>
        /// 结束任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void EndTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string ids = "";

            foreach (var item in dictEndTask)
            {
                if (item.Value.EndTime <= DateTime.Now)
                    ids += "," + item.Value.ID;
            }

            if (!string.IsNullOrEmpty(ids))
            {
                ids = ids.Substring(1);
                bool isSuccess = dal.Update(ids);

                //删除待结束结合中的项
                if (isSuccess)
                {
                    string[] indexes = new string[] { };
                    if (ids.IndexOf(',') > 0)
                        indexes = ids.Split(',');
                    else
                        indexes = new string[] { ids };

                    foreach (var item in indexes)
                    {
                        int id = Convert.ToInt32(item);
                        dictEndTask.Remove(id);
                        //释放该场比赛的机器人计时器
                        if (dictTimerController.ContainsKey(id))
                        {
                            dictTimerController[id].Dispose();
                            dictTimerController.Remove(id);
                        }
                    }
                }
            }
        }
        #endregion


        public void EditTaskRobotScore(TaskRobotSetting model)
        {
            if (!dictTimerController.ContainsKey(model.TaskID.Value))
            {
                //该任务已开始
                if (dictEndTask.ContainsKey(model.TaskID.Value))
                {
                    dictTimerController[model.TaskID.Value] = new TaskRobotController(model);
                }
            }
            else
            {
                dictTimerController[model.TaskID.Value].settingModel = model;
            }
        }
    }
}
